package com.xbongbong.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class HttpRequestUtils {

	public static String post(String url, JSONObject jsonObject) {
		return post(HeaderUtil.getHeader(), url, jsonObject.entrySet().stream().filter(v -> v.getValue()!=null).map(
				v->String.join("=",v.getKey(),v.getValue().toString())
		).collect(Collectors.joining("&")));
	}
	
	// post提交表单
	public static String post(JSONObject header, String url, String param) {

		String body = null;
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);

		addHeader(httppost, header);

		//参数设置
		RequestConfig requestConfig = RequestConfig.custom()
		        .setConnectTimeout(10000)
		        .setSocketTimeout(10000).build();
		httppost.setConfig(requestConfig);
		try {

			StringEntity uefEntity = new StringEntity(param, "UTF-8");
			uefEntity.setContentType("application/json");
			httppost.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);

			try {

				HttpEntity entity = response.getEntity();
				if (entity != null) {
					body = EntityUtils.toString(entity, "UTF-8");
				}

			} finally {
				response.close();
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return body;
	}

	/**
	 * 置入header信息
	 * @param httppost
	 * @param header header信息
	 * 创建时间 2020/2/25 10:11 AM
	 * 修改时间 2020/2/25 10:11 AM
	 * @author chy
	 */
	private static void addHeader(HttpRequestBase httppost, JSONObject header) {
		if (Objects.isNull(header) || header.isEmpty()) {
			return;
		}
		Set<String> keySet = header.keySet();
		for (String key : keySet) {
			String value = header.getString(key);
			httppost.addHeader(key, value);
		}
	}

	// 给请求
	public static String get(JSONObject header, String url) {
		String body = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			addHeader(httpget, header);
			// 执行get请求.
			response = httpclient.execute(httpget);
			// 获取响应实体
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				body = EntityUtils.toString(entity);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return body;
	}
	public static String get(JSONObject header,URIBuilder uriBuilder) {
		String body = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(uriBuilder.build());
			addHeader(httpget, header);
			// 执行get请求.
			response = httpclient.execute(httpget);
			// 获取响应实体
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				body = EntityUtils.toString(entity);
			}
		} catch (ClientProtocolException | URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return body;
	}

	/**
	 * 删除请求
	 * @param header
	 * @param url
	 * @return
	 */
	public static String delete(JSONObject header, String url) {

		String body = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			// 创建httpDelete.
			HttpDelete httpDelete = new HttpDelete(url);
			addHeader(httpDelete, header);
			// 执行请求.
			response = httpclient.execute(httpDelete);
			// 获取响应实体
			HttpEntity entity = response.getEntity();
			//System.out.println("--------------------------------------");
			// 打印响应状态
			//System.out.println(response.getStatusLine());

			if (entity != null) {
				body = EntityUtils.toString(entity);
				// 打印响应内容长度
				//System.out.println("Response content length: " + entity.getContentLength());
				// 打印响应内容
				//System.out.println("Response content: " + body);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return body;
	}

	public static String put(String url, JSONObject jsonObject) {
		return put(HeaderUtil.getHeader(), url, jsonObject.entrySet().stream().filter(v -> v.getValue()!=null).map(
				v->String.join("=",v.getKey(),v.getValue().toString())
		).collect(Collectors.joining("&")));
	}
	
	//put提交表单
	public static String put(JSONObject header, String url, String param) {
		String body = null;
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPut httpPut = new HttpPut(url);
		addHeader(httpPut, header);
		//参数设置
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(10000)
				.setSocketTimeout(10000).build();
		httpPut.setConfig(requestConfig);
		try {
			StringEntity uefEntity = new StringEntity(param, "UTF-8");
			uefEntity.setContentType("application/json");
			httpPut.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httpPut);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					body = EntityUtils.toString(entity, "UTF-8");
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException | UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return body;
	}
}
